/**
 * @author Yuliy Khorolinskyy
 *
 * Reaktionsspiel scaler
 *
 * 16.01.2012
 */
package scaler;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import control.SimpleTimer;

/**
 * @author Yuliy
 * This class realizes automatic GUI scaling for game elements.
 *
 */
public class Scaler {
	
	public static final Scaler NO_SCALING = new Scaler(new Dimension(100, 100));
	
	public final Dimension dim;
	private float xScale = 1;
	private float yScale = 1;
	private Scaler inlaySc;
	
	public Scaler(Dimension origDim, Dimension currentDim) {
		this.dim = origDim;
		rescaleDim(currentDim);
	}
	
	public Scaler(Dimension origDim) {
		this.dim = origDim;
	}
	
	public Scaler(Dimension origDim, Dimension currentDim, Scaler inlay){
		this.dim = origDim;
		rescaleDim(currentDim);
		this.inlaySc = inlay;
	}
	
	public Scaler(Dimension origDim, Scaler inlay) {
		this.dim = origDim;
		this.inlaySc = inlay;
	}
	
	public Scaler(Dimension origDim, Component observable){
		this(origDim);
		this.watchComponentSize(observable);
	}
	
	public Scaler(Dimension origDim, Scaler inlay, Component observable){
		this(origDim, inlay);
		this.watchComponentSize(observable);
	}
	
	public void watchComponentSize(final Component observable){
		observable.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				Scaler.this.rescaleDim(observable.getSize());
			}
			
		});
		
		Scaler.this.rescaleDim(observable.getSize());
		
//		SimpleTimer.pause(1,new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent arg0) {
//	
//				
//			}
//		});

	}
	
	public int calcX(int origX){
		if(inlaySc != null)	return Math.round(inlaySc.calcX(origX)*xScale);
		else return Math.round(origX*xScale);
	}
	
	public int calcY(int origY){
		if(inlaySc != null) return Math.round(inlaySc.calcY(origY)*yScale);
		else return Math.round(origY*yScale);
	}
	
	public void rescaleDim(Dimension newCurrentDim) {
		this.rescaleX(newCurrentDim.getWidth());
		this.rescaleY(newCurrentDim.getHeight());
	}
	
	public void rescaleX(double newCurrentWidth){
		this.xScale = (float)(newCurrentWidth/dim.getWidth());
	}
	
	public void rescaleY(double newCurrentHeight){
		this.yScale = (float)(newCurrentHeight/dim.getHeight());
	}
}
